package com.nkdx.ws.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.nkdx.ws.dto.UserDto;
import com.nkdx.ws.enums.CodeEnum;
import com.nkdx.ws.exception.DataException;
import com.nkdx.ws.mapper.UserMapper;
import com.nkdx.ws.service.LoginService;
import com.nkdx.ws.util.Utils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;

/**
 *
 *   登录业务
 * @author ZZW
 * @date 2022/3/2 3:59 下午
 * @param
 * @return
 */

@Service
public class LoginServiceImpl implements LoginService {

    private UserMapper userMapper;

    private HttpServletRequest request;

    @Autowired
    public LoginServiceImpl (HttpServletRequest request,UserMapper userMapper){
        this.request = request;
        this.userMapper = userMapper;
    }

    @Override
    public boolean login() {
        UserDto user =(UserDto) request.getSession().getAttribute("user");
        if (user != null){
            return true;
        }
        try {
            loginVerification();
            return true;
        }catch (DataException e){
            return false;
        }
    }

    /**
     *
     *  登录校验
     * @author ZZW
     * @date 2022/3/3 10:16 上午
     * @param
     * @return
     */

    @Override
    public JSONObject loginVerification() {
        JSONObject data = new JSONObject();
        String name = request.getParameter("name");
        String password = request.getParameter("password");
        if (StringUtils.isNotBlank(name) && StringUtils.isNotBlank(password)){
            UserDto userDto = userMapper.findUserByName(name);
            String md5 = Utils.MD5(password);
            if (userDto != null && Utils.MD5(password).equals(userDto.getPassword())){
                data.put("user",userDto);
                data.put("userType",userDto);
                request.getSession().setAttribute("user",userDto);
                if (userDto.getId() != null){
                    userMapper.updateUserLastLoginTime(userDto.getId(),new Date());
                }
            }else {
                throw new DataException(CodeEnum.LOGIN_PWD_ERROR);
            }
        }else {
            throw new DataException(CodeEnum.COM_MISS_PARAM_ERROR);
        }
        return data;
    }

    @Override
    public void logout() {
        request.getSession().invalidate();
    }
}
